#include "selectstockw.h"

#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QVBoxLayout>
#include <QStandardItem>
#include <QDebug>

#include "HttpClient.hpp"


QString serverAddr = "http://192.168.0.109:8888";
SelectStockW::SelectStockW(QWidget *parent) : QWidget(parent)
{
    initUI();
    initData();
    createConnect();

    //gotoPage(0);
}


void SelectStockW::onBtnSearchClick(bool)
{
    gotoPage(0);
}

void SelectStockW::onNextPage()
{
    QStringList list =  l_curPage->text().split("/");
    int pageNum =0;
    if(list.size())
    {
        pageNum = list[0].toInt();
    }
/*
    if(pageNum == 0)
    {
        return;
    }
   */
    gotoPage(pageNum++);
}

void SelectStockW::onPrePage()
{
    QStringList list =  l_curPage->text().split("/");
    int pageNum =0;
    if(list.size())
    {
        pageNum = list[0].toInt();
    }

    if(pageNum == 0)
    {
        return;
    }

    gotoPage(--pageNum);
}

void SelectStockW::updateStockList(QString& startDate, QString& endDate,int upDivChange,int pageNum,int markValStart, int markValEnd,int tradeRatio,int upRatio)
{
    QString url=serverAddr+"/ranklist?"; //看来前缀必须要添加http
    url += QString("startdate=%1&enddate=%2&pagenum=%3&upDivChange=%4&marketValStart=%5&marKetValEnd=%6&changeRatio=%7&upRatio=%8")
            .arg(startDate).arg(endDate).arg(pageNum).arg(upDivChange).arg(markValStart).arg(markValEnd).arg(tradeRatio).arg(upRatio);
    qDebug() << "url:" << url;
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/x-www-form-urlencoded"));

    QNetworkReply::NetworkError networkError;
    QByteArray response;

    int rlt = HttpClient::syncGet(request,networkError, response);

    if(rlt != HCE_OK)
    {
        qDebug() << "GetPaperList failed. syncPost error: %d" <<  networkError << response.data();
        return;
    }

    //{"日期","代码","名称","市值","换手率","涨跌幅"};
    QJsonDocument jsonDocResponse = QJsonDocument::fromJson(response);
    if(jsonDocResponse.isNull() || jsonDocResponse.isEmpty())
    {
        qDebug() << "response invalid. response: %s" <<  response.data();
        return;
    }

    //清除除表头所有数据
    int rowCount = tableView->getModel()->rowCount();
    if(rowCount > 0)
    {
        tableView->getModel()->removeRows(0, rowCount);
    }

    QJsonObject json = jsonDocResponse.object();


    if(json.contains("RankList"))
    {
        QJsonArray skillsArray = json["RankList"].toArray();
        int i =0;
        for(; i< skillsArray.size(); i++)
        {
               QJsonObject jsonData =  skillsArray.takeAt(i).toObject();

               int col =0;
               if(jsonData.contains("Date"))
               {
                   QStandardItem *newItem = new QStandardItem(jsonData.value("Date").toString());
                   tableView->getModel()->setItem(i, col, newItem);
               }

               col++;

               if(jsonData.contains("Code"))
               {
                   QStandardItem *newItem = new QStandardItem(jsonData.value("Code").toString());
                   tableView->getModel()->setItem(i, col, newItem);
               }
               col++;

               if(jsonData.contains("Name"))
               {
                   QStandardItem *newItem = new QStandardItem(jsonData.value("Name").toString());
                   tableView->getModel()->setItem(i, col, newItem);
               }

               col++;

               if(jsonData.contains("MarketVal"))//市值
               {
                   QStandardItem *newItem = new QStandardItem(jsonData.value("MarketVal").toString());
                   tableView->getModel()->setItem(i, col, newItem);
               }

               col++;
               double dChangeRatio = 0;
               if(jsonData.contains("ChangeRatio")) //涨跌幅
               {
                   QString strChangeRatio = jsonData.value("ChangeRatio").toString();
                   QStandardItem *newItem = new QStandardItem(strChangeRatio);

                   strChangeRatio.chop(1);

                   dChangeRatio =strChangeRatio.toDouble();
                   tableView->getModel()->setItem(i, col, newItem);

               }

               col++;

               double dTradeRatio = 0;//换手率
               if(jsonData.contains("TradeChangeRatio"))
               {
                   QString strTradeRatio = jsonData.value("TradeChangeRatio").toString();
                   QStandardItem *newItem = new QStandardItem(strTradeRatio);

                   strTradeRatio.chop(1);
                   dTradeRatio =strTradeRatio.toDouble();
                   tableView->getModel()->setItem(i, col, newItem);
               }


               col++;

               if(jsonData.contains("PriceNominal"))//价格
               {
                   QStandardItem *newItem = new QStandardItem(jsonData.value("PriceNominal").toString());
                   tableView->getModel()->setItem(i, col, newItem);
               }

               col++;

               if(jsonData.contains("TradeTrunover"))//成交额
               {
                   QStandardItem *newItem = new QStandardItem(jsonData.value("TradeTrunover").toString());
                   tableView->getModel()->setItem(i, col, newItem);
               }

               col++;

               if(jsonData.contains("TradeVolumn"))//成交量
               {
                   QStandardItem *newItem = new QStandardItem(jsonData.value("TradeVolumn").toString());
                   tableView->getModel()->setItem(i, col, newItem);
               }

               col++;

               //涨跌幅/换手率
               QStandardItem *newItem = new QStandardItem(QString::number(dChangeRatio/dTradeRatio,'f',2));
               tableView->getModel()->setItem(i, col, newItem);
        }
    }

    QString totalPage,CurPageNum;
    if(json.contains("TotalCount"))
    {
        totalPage = QString::number(json.value("TotalCount").toInt());
    }

    if(json.contains("CurPageNum"))
    {
        CurPageNum = QString::number(json.value("CurPageNum").toInt());
    }
    qDebug() <<  totalPage << " " << CurPageNum;
    l_curPage->setText(CurPageNum + "/" +totalPage);
}

void SelectStockW::gotoPage(int num)
{
    int upDivChange = lchang_div_trade->text().toInt();
    QString start = lstartdate->text();
    QString end = lenddate->text();
    int markValStart = line_startMarketVal->text().toInt();
    int markValEnd = line_endMarkteVal->text().toInt();
    int tradeRatio = line_changeRatio->text().toInt();
    int upRatio = line_upRatio->text().toInt();
    updateStockList(start,end,upDivChange,num,markValStart,markValEnd,tradeRatio,upRatio);
}

void SelectStockW::initUI()
{
    setWindowTitle("选股器");

    tableView = new FreezeTableWidget(this);
    lstartdate = new QLineEdit(this);
    lstartdate->setMaximumWidth(100);
    lchang_div_trade= new QLineEdit(this);
    lchang_div_trade->setMaximumWidth(60);
    lenddate= new QLineEdit(this);
    lenddate->setMaximumWidth(100);

    line_startMarketVal= new QLineEdit(this);

    line_startMarketVal->setFixedWidth(60);
    line_endMarkteVal= new QLineEdit(this);
    line_endMarkteVal->setFixedWidth(60);

    line_changeRatio= new QLineEdit(this);
    line_changeRatio->setMaximumWidth(40);
    line_upRatio= new QLineEdit(this);
    line_upRatio->setMaximumWidth(40);
    l_curPage = new QLabel(this);

    btn_search = new QPushButton(this);
    btn_search->setText("搜索");
    btn_search->setFixedWidth(60);
    btn_next = new QPushButton(this);
    btn_next->setFixedWidth(60);
    btn_next->setText("下一页");
    btn_pre = new QPushButton(this);
    btn_pre->setFixedWidth(60);
    btn_pre->setText("上一页");

    QLabel *labelStart = new QLabel(this);
    labelStart->setText("开始日期");

    QLabel *labelEnd = new QLabel(this);
    labelEnd->setText("开始日期");

    QLabel *Up = new QLabel(this);
    Up->setText("涨跌幅");

    QLabel *l;
    QVBoxLayout *v = new QVBoxLayout(this);
    QHBoxLayout* h1 =  new QHBoxLayout(this);
    h1->setSpacing(10);
     h1->addWidget(labelStart);
    h1->addWidget(lstartdate);
     h1->addWidget(labelEnd);
    h1->addWidget(lenddate);
    h1->addStretch();
     h1->addWidget(Up);
    h1->addWidget(line_upRatio);
    h1->addWidget(Up);
    l = new QLabel(this);
    l->setText("换手率");
    h1->addWidget(l);
    h1->addWidget(line_changeRatio);


    l = new QLabel(this);
    l->setText("涨幅/换手率");
    h1->addWidget(l);
     h1->addWidget(lchang_div_trade);


    QHBoxLayout* h2 =  new QHBoxLayout(this);
    l = new QLabel(this);
    l->setText("市值");
    h2->addWidget(l);
    h2->addWidget(line_startMarketVal);
    h2->addWidget(line_endMarkteVal);
    h2->addStretch();

    QHBoxLayout* h3 =  new QHBoxLayout(this);
    h3->addStretch();
    h3->addWidget(btn_pre);
    l_curPage->setText("0/0");
    h3->addWidget(l_curPage);
    h3->addWidget(btn_next);
    h3->addStretch();
    h3->addWidget(btn_search);


    v->addLayout(h1);
    v->addLayout(h2);
    v->addLayout(h3);
    v->addWidget(tableView);
}

void SelectStockW::initData()
{
    QDate currentDate = QDate::currentDate().addDays(-1);
    QString strCurDate=  currentDate.toString("yyyy-MM-dd");
    lstartdate->setText(strCurDate);
    lenddate->setText(strCurDate);

}

void SelectStockW::createConnect()
{
    QObject::connect(btn_search,&QPushButton::clicked, this, &SelectStockW::onBtnSearchClick);
    QObject::connect(btn_next,&QPushButton::clicked, this, &SelectStockW::onNextPage);
    QObject::connect(btn_pre,&QPushButton::clicked, this, &SelectStockW::onPrePage);
}
